package servlets;

import java.io.InputStream;

import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import managers.DatabaseManager;
import managers.JSonManager;
import structures.AD;

@MultipartConfig
public class CreateNewADServlet extends HttpServlet {
	     
	private static final long serialVersionUID = -6102424829136725930L;
	     
	    protected void doPut(HttpServletRequest request, HttpServletResponse response) {
	    	String description, title, price, jsonResult,idUser, payPalEmail;
	    	InputStream inputStream;
	    	AD advertisement;
	    	Part filePart;
	    	JSonManager jSonManager;
			jSonManager = new JSonManager();
	        // gets values of text fields
	    	description = request.getParameter("description");
	    	title = request.getParameter("title");
	    	price = request.getParameter("price");
	    	idUser = request.getParameter("idUser");
	    	payPalEmail = request.getParameter("payPalEmail");
	        inputStream = null; // input stream of the upload file
	        try {
	        	// obtains the upload file part in this multipart request
				filePart = request.getPart("photo");
	        
		        if (filePart != null) {
		            // obtains input stream of the upload file
		            inputStream = filePart.getInputStream();
		        }
		        response.setContentType("application/json");
				response.setCharacterEncoding("UTF-8");
		        DatabaseManager databaseManager;
				databaseManager = new DatabaseManager();
				databaseManager.connect();
				advertisement = databaseManager.insertAD(description, inputStream, title, price,idUser, payPalEmail);
				jsonResult = jSonManager.generateJSON(advertisement);
				response.getWriter().write(jsonResult);
				databaseManager.closeConnection();
		        
	        } catch (Exception e) {
				e.printStackTrace();
			}
	    }
	}